import pygame
import random
from src.elements.map import GameMap, get_default_map
from src.elements.player import PlayerTank
from src.elements.enemy import EnemyTank
from src.elements.fruit import Fruit

# 定义不同等级的敌人坦克类型
ENEMY_TYPES = ["enemy_1", "enemy_2", "enemy_3", "enemy_4"]
MIN_DISTANCE_FROM_PLAYER = 150  # 定义敌方坦克与玩家坦克的最小距离

def get_default_enemies(game_map, player_rect):
    enemies = []
    num_enemies = 2  # 初始生成2个敌人坦克
    for _ in range(num_enemies):
        enemy_type = random.choice(ENEMY_TYPES)
        while True:
            x = random.randint(0, 768)  # 随机生成x坐标
            y = random.randint(0, 568)  # 随机生成y坐标
            enemy = EnemyTank(x, y, enemy_type)
            # 检查生成位置是否有效，确保坦克不会卡在墙里且与玩家坦克距离足够远
            if is_valid_spawn_position(game_map, enemy.rect) and is_far_enough_from_player(player_rect, enemy.rect):
                enemies.append(enemy)
                break
    return enemies

def is_valid_spawn_position(game_map, rect):
    # 检查生成位置是否有效，确保坦克不会卡在墙里
    return game_map.check_collision(rect) is None

def is_far_enough_from_player(player_rect, enemy_rect):
    # 计算敌方坦克与玩家坦克的距离
    distance = ((player_rect.centerx - enemy_rect.centerx) ** 2 + (player_rect.centery - enemy_rect.centery) ** 2) ** 0.5
    return distance >= MIN_DISTANCE_FROM_PLAYER

class GameScreen:
    def __init__(self, screen, map_data=None):
        self.screen = screen
        if map_data is None:
            map_data = get_default_map()
        self.map = GameMap(map_data)
        self.player = PlayerTank((300, 500))
        self.enemies = get_default_enemies(self.map, self.player.rect)
        self.fruits = pygame.sprite.Group()
        self.generate_fruit()
        self.enemy_defeated_time = []  # 记录敌方坦克被击败的时间

    def generate_fruit(self):
        """生成果实"""
        while True:
            x = random.randint(0, 768)  # 随机生成x坐标
            y = random.randint(0, 568)  # 随机生成y坐标
            fruit = Fruit(x, y)
            if is_valid_spawn_position(self.map, fruit.rect):
                self.fruits.add(fruit)
                break

    def generate_enemy(self):
        """生成新的敌方坦克"""
        MAX_ENEMIES = 20  # 敌方坦克的最大数量
        if len(self.enemies) < MAX_ENEMIES:
            enemy_type = random.choice(ENEMY_TYPES)
            while True:
                x = random.randint(0, 768)  # 随机生成x坐标
                y = random.randint(0, 568)  # 随机生成y坐标
                enemy = EnemyTank(x, y, enemy_type)
                if is_valid_spawn_position(self.map, enemy.rect) and is_far_enough_from_player(self.player.rect, enemy.rect):
                    self.enemies.append(enemy)
                    break

    def run(self):
        running = True
        clock = pygame.time.Clock()

        while running:
            current_time = pygame.time.get_ticks()
            # 检查是否有敌方坦克被击败1秒后需要刷新
            for defeated_time in self.enemy_defeated_time[:]:
                if current_time - defeated_time >= 1000:
                    self.generate_enemy()
                    self.enemy_defeated_time.remove(defeated_time)

            clock.tick(60)
            self.screen.fill((0, 0, 0))
            self.map.draw(self.screen)

            keys_pressed = pygame.key.get_pressed()
            self.player.update(keys_pressed, self.map)
            if keys_pressed[pygame.K_SPACE]:
                self.player.shoot()

            # 更新玩家子弹
            self.player.bullets.update(self.map)

            self.player.draw(self.screen)

            for enemy in self.enemies[:]:
                enemy.update(self.map)
                enemy.draw(self.screen)

            # 检测玩家炮弹与敌方坦克的碰撞
            for bullet in self.player.bullets:
                for enemy in self.enemies[:]:
                    if bullet.rect.colliderect(enemy.rect):
                        if enemy.hit(bullet.damage):
                            self.enemies.remove(enemy)
                            self.enemy_defeated_time.append(pygame.time.get_ticks())  # 记录敌方坦克被击败的时间
                            # 当击败等级为4的敌方坦克时，生成一个新的果实
                            if enemy.type == "enemy_4":
                                self.generate_fruit()
                        bullet.active = False

            # 检测敌方炮弹与玩家坦克的碰撞
            for enemy in self.enemies:
                for bullet in enemy.bullets:
                    if bullet.rect.colliderect(self.player.rect):
                        if self.player.hp > 0:
                            self.player.hp -= bullet.damage
                        if self.player.hp <= 0:
                            if self.player.extra_lives > 0:
                                # 使用备用坦克
                                self.player.extra_lives -= 1
                                self.player.hp = 1
                                self.player.rect.center = (300, 500)  # 重置玩家位置
                            else:
                                print("Game Over: Player tank destroyed!")
                                return False
                        bullet.active = False

            # 检测玩家与果实的碰撞
            collided_fruits = pygame.sprite.spritecollide(self.player, self.fruits, True)
            for fruit in collided_fruits:
                result = fruit.picked_up(self.player)
                if result == 'extra_life':
                    print("Player got an extra life!")

            self.fruits.draw(self.screen)

            pygame.display.flip()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

            # 检查司令部是否被摧毁
            if self.map.check_home_destroyed():
                print("Game Over: Home destroyed!")
                return False

            # 检查敌人坦克是否全部被击败
            if len(self.enemies) == 0:
                print("Game Success: All enemies defeated!")
                return "success"

        return True